import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Select, Space, Table, Tag } from 'antd';

import Filter from '@/components/filter';
import Text from '@/components/text';
import Upload from '@/components/upload';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { StatusObj } from '@/enum/product';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equRepairRegularRecordPage,
  equRepairRegularRecordStatistics
} from '@/services/bizApi/shebaodingqijianxiujilujiekou';

import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.EquRepairRegularRecordEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const [filter] = Filter.useForm();
  const [statisticsCondition, setStatisticsCondition] = useState('');
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const statistic = useRequest(
    async () => {
      const res = await equRepairRegularRecordStatistics();

      return res?.data || {};
    },
    {
      refreshDeps: []
    }
  );

  const statisticSearch = (condition: string) => () => {
    table.search.reset();
    if (statisticsCondition === condition) {
      setStatisticsCondition('');
    } else {
      setStatisticsCondition(condition);
    }
    table.search.submit();
  };
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await equRepairRegularRecordPage({
        ...formData,
        ...id,
        statisticsCondition,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    setStatisticsCondition('');
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/**统计 */}
      <Space size={16} style={{ marginBottom: '20px', fontWeight: 'bold', cursor: 'pointer' }}>
        <div
          onClick={statisticSearch('1')}
          style={{ color: statisticsCondition === '1' ? 'var(--ant-color-primary)' : '' }}
        >
          <span>总数：</span>
          <Text>{statistic.data?.value1 || 0}</Text>
        </div>
        <div
          onClick={statisticSearch('2')}
          style={{ color: statisticsCondition === '2' ? 'var(--ant-color-primary)' : '' }}
        >
          <span>未完成数：</span>
          <Text>{statistic.data?.value2 || 0}</Text>
        </div>
      </Space>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="dutyUserId">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择负责人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Filter.Item>
        <Filter.Item name="status">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择状态"
            options={[
              {
                label: '待处理',
                value: 1
              },
              {
                label: '已完成',
                value: 3
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '负责人',
            dataIndex: 'dutyUserName'
          },
          {
            title: '详情',
            dataIndex: 'content'
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = StatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '处理情况',
            dataIndex: 'handleSituation'
          },
          {
            title: '附件',
            dataIndex: 'attachment',
            render: (url) => {
              if (!url || url === '-') return;
              return (
                <Upload
                  disabled
                  value={url as unknown as string}
                  // base64
                  //  accept="image/*"
                  maxCount={1}
                >
                  {/* <Button>上传附件</Button> */}
                </Upload>
              );
            },
            width: 200
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() &&
                    row?.status === 1 &&
                    store?.user?.id === row?.dutyUserId && (
                      <Text
                        onClick={() => {
                          dispose.current?.open({
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        处置
                      </Text>
                    )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
    </>
  );
};

export default Page;
